package com.github.thinwonton.showcase.springboot.jpa.service;

import com.github.thinwonton.showcase.springboot.jpa.domain.Account;
import com.github.thinwonton.showcase.springboot.jpa.domain.AccountRepository;
import com.github.thinwonton.showcase.springboot.jpa.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountService {
    @Autowired
    private AccountRepository accountRepository;

    @Transactional(rollbackFor = Exception.class)
    public void save(Account account) throws BizException {
        accountRepository.save(account);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(Account account) {
        accountRepository.save(account);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        accountRepository.delete(id);
    }

    public Account getById(Long id) {
        return accountRepository.getOne(id);
    }

    public List<Account> list() {
        return accountRepository.findAll();
    }

    public Page<Account> listPage(int pageNumber, int pageSize) {
        Pageable pageable = new PageRequest(pageNumber, pageSize);
        return accountRepository.findAll(pageable);
    }
}
